package com.project.poetry.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.poetry.common.config.ConfigProperties;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.constant.DictConstant;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.dto.login.LoginUserDTO;
import com.project.poetry.service.entity.dto.login.RegUserDTO;
import com.project.poetry.service.entity.po.user.UserPO;
import com.project.poetry.service.mapper.UserMapper;
import com.project.poetry.service.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 登录，注册业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginServiceImpl implements LoginService {

    @Resource
    private ConfigProperties configProperties;

    @Resource
    private UserMapper userMapper;

    @Override
    public void register(RegUserDTO userDTO) {
        Integer nameMaxLength = this.configProperties.getNameMaxLength();
        CommonUtil.checkThrow(name -> name.length() > nameMaxLength, userDTO.getUsername(),
                ConstantValue.REG_ERROR_STATUS_CODE,String.format("用户名不可超过 %d 位！！！", nameMaxLength));
        String loginId = userDTO.getLoginId();
        UserPO user = this.userMapper.selectOne(new QueryWrapper<UserPO>().lambda()
                .eq(UserPO::getLoginId, loginId));
        CommonUtil.checkThrow(Objects::nonNull, user, ConstantValue.REG_ERROR_STATUS_CODE,"用户已存在！！！");
        user = new UserPO();
        String password = userDTO.getPassword();
        BeanUtils.copyProperties(userDTO, user);
        user.setRealPassword(password);
        user.setPassword(CommonUtil.md5String(password));
        user.setIsVip(DictConstant.FALSE);
        this.userMapper.insert(user);
    }

    @Override
    public void login(LoginUserDTO userDTO) {
        String loginId = userDTO.getLoginId();
        UserPO user = this.userMapper.selectOne(new QueryWrapper<UserPO>().lambda()
                .eq(UserPO::getLoginId, loginId));
        CommonUtil.checkThrow(Objects::isNull, user,
                ConstantValue.LOGIN_ERROR_STATUS_CODE, String.format("您输入的账号：%s不存在！请重新登录", loginId));
        String password = userDTO.getPassword();
        CommonUtil.checkThrow(u -> !u.getPassword().equals(CommonUtil.md5String(password)), user,
                ConstantValue.LOGIN_ERROR_STATUS_CODE,
                String.format("您输入的密码：%s不正确！请重新登录", password));
        CommonUtil.saveUser(user);
    }

    @Override
    public void logout() {
        CommonUtil.logout();
    }
}
